<?php
namespace app\mini\model;

use think\facade\Db;
use app\common\traits\ActionRecordTrait;
use think\Model;
use app\admin\controller\ApiCommon;

use app\crm\model\CustomerLossModel;
use app\crm\model\OrderStatistics;
use app\admin\model\ShopOrderModel;
use app\admin\model\CustomerModel;
use app\admin\model\ShopModel;
use app\shop\model\Refund as OrderModel;
use app\mini\model\MiniStisticsModel;
use app\crm\model\ReserveandLost;



class SysModelMini extends Model

{



    /**

     * @var string

     */

    protected $name = 'admin_sys';



    protected $defaultSoftDelete = 0;



    protected $autoWriteTimestamp = true;



    /**

     * 获取系统首页信息资源

     * @return array

     * @author ran

     * @date 2021-09-23 13:53

     * mailbox 466180170@qq.com

     */

    public function getAdminSysHomeInfoResource($request): array
    {
        // echo "<pre>";
        // print_r($request['shop_id']);
        // echo "</pre>";
        
        $startTime = !empty($request['startTime']) ? strtotime($request['startTime']) : strtotime(date('Y-m-01',time()));
        $endTime = !empty($request['endTime']) ? strtotime($request['endTime'].' 23:59:59') : strtotime(date('Y-m-t 23:59:59',time()));

        // echo $startTime."<br/>";
        // echo $endTime."<br/>";
        // exit;

        $orderModel = new ShopOrderModel();

        $is_shop_array = ['2' => 1,'1' =>2];

        if(is_array($request['shop_id'])){
            // echo "1";

            $shopIds = $request['shop_id'];

        }else{
            // echo "2";

            $shopIds = json_decode($request['shop_id'],true) ?? array();

        }

        // echo "<pre>";
        // print_r($shopIds);
        // echo "</pre>";
        // exit;

        if(is_array($shopIds)){

            $amountData = []; // 总
            $amountNewData = []; // 新
            $amountRepairData = []; // 补

            foreach ($shopIds as $key => $value) {

                $newShopIds = [];

                array_push($newShopIds,$value);

                $is_medical = Db::name('shop')->where('shop_id',$value)->value('shop_type');

                $isShop = $is_shop_array[$is_medical];

                $newRequest = [];

                $newRequest['startTime'] = $startTime;
                $newRequest['endTime'] = $endTime;
                $newRequest['isShop'] = $isShop;

                $order = $orderModel->miniHomeOrder($newShopIds, $newRequest);

                array_push($amountData,$order['amount']);
                array_push($amountNewData,$order['amountNew']);
                array_push($amountRepairData,$order['amountRepair']);

            }

            $res = [

                'amount' => bcadd(array_sum($amountData),0,2),

                'amountNew' => bcadd(array_sum($amountNewData),0,2),

                'amountRepair' => bcadd(array_sum($amountRepairData),0,2),

            ];

        }else{

            $newShopIds = [];

            array_push($newShopIds,$shopIds);
            
            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->value('shop_type');

            $isShop = $is_shop_array[$is_medical];

            $newRequest = [];

            $newRequest['startTime'] = $startTime;
            $newRequest['endTime'] = $endTime;
            $newRequest['isShop'] = $isShop;

            $order = $orderModel->miniHomeOrder($newShopIds, $newRequest);

            $res = [

                'amount' => bcadd($order['amount'],0,2),  //当前店铺集合支付总金额

                'amountNew' => bcadd($order['amountNew'],0,2), //新单

                'amountRepair' => bcadd($order['amountRepair'],0,2), //补单

            ];
        }

        return $res;

    }

    /**
     * 首页客户数据查询
     */
    public function getHomeCustomer($shopIds,$request): array
    {
        $isShop = $request['isShop'] ?? 0;

        // $startTime = strtotime(date('Y-m-01',time()));
        // $endTime = strtotime(date('Y-m-t 23:59:59',time()));

        $startTime = !empty($request['startTime']) ? strtotime($request['startTime']) : strtotime(date('Y-m-01',time()));
        $endTime = !empty($request['endTime']) ? strtotime($request['endTime'].' 23:59:59') : strtotime(date('Y-m-t 23:59:59',time()));

        $orderModel = new ShopOrderModel();
        $customerModel = new CustomerModel();
        
        $customerComeIn = $customerModel->getCustomerCollect('count',$shopIds,$startTime,$endTime,$isShop);
        
        $cjCustomer = $orderModel->getShopOrderCollect('count', $shopIds, $startTime, $endTime, $isShop);

        $serNum = 0;
        foreach ($shopIds as $key => $value) {

            // 护理量查询
            $service = Db::name('service_log')->where([['shop_id', '=', $value], ['create_time', 'between', "$startTime,$endTime"],['category_id','in',[1,8,10,11,4,12]]])->count();

            // echo $service;echo "<br/>";

            $serNum = bcadd($serNum,$service,0);

        }

        // exit;

        // if(!empty($service)){

        //     $service = array_column($service,null,'shop_id');

        // }else{

        //     $service[$shopIds[0]]['sum'] = '0';

        // }

        return [

            'customerComeIn' => $customerComeIn,

            'cjCustomer' => $cjCustomer,

            // 'service' => $service[$shopIds[0]]['sum'],

            'service' => $serNum,

        ];
    }


    /**
     * 首页保有数据查询
     */
    public function getHomeBaoyou($shopIds,$request): array
    {
        // 保有顾客数
        $date = date('Y-m-d',time());

        $model = new ReserveandLost();

        // $cj_customer_all = $model->cj_customer($shopIds,[]);

        $cj_customer = $model->cj_customer($shopIds,[]);

        $baoyou_customer = $model->baoyou_customer($cj_customer,$date);

        $warning_customer = $model->warning_customer($cj_customer,$date,'','','');

        $lost_customer = $model->lost_customer($cj_customer,$date);

        $tenure = count($baoyou_customer);

        $warning_customerN = count($warning_customer);

        $lost_customerN = count($lost_customer);


        $shopModel = new ShopModel();
        $shopModeRes = $shopModel->getAdminShopStatistics($shopIds,(int)$request['page']='',(int)$request['limit']='',$request);
        // 项目普及率

        

        $data = $shopModeRes['list'][0]['list'];

        // echo "<pre>";
        // print_r($shopModeRes);
        // echo "</pre>";
        // exit;

        $popularityRate = bcadd(str_replace('%','',$data[0]['popularityRate']),0,2);
        $gongxiaomanyi = bcadd(str_replace('%','',$data[0]['gongxiaomanyi']),0,2);
        $baoyouRate = ''.bcdiv(count($baoyou_customer),count($cj_customer),4)*100;
        
        return [

            'tenure' => $tenure,

            'popularityRate' => $popularityRate,

            'gongxiaomanyi' => $gongxiaomanyi,

            'baoyouRate' => $baoyouRate,

            'warning_customerN' => $warning_customerN,

            'lost_customerN' => $lost_customerN,

        ];
    }

    /**
     * 客户的消费记录
     */
    public function costList($request)
    {
        $orderModel = new OrderModel();

        // 收款单
        $skResquest = $request;
        $skResquest['type'] = '3';

        $skData = $orderModel->getDataList($skResquest);
        
        $skList = isset($skData['list'])?$skData['list']:[];
      
        // 退款单
        $tkResquest = $request;
        $tkResquest['type'] = '1';

        $tkData = $orderModel->getDataList($tkResquest);

        $tkList = isset($tkData['list'])?$tkData['list']:[];

        $newList = $skList;
        foreach ($tkList as $key => $value) {
            array_push($newList,$value);
        }

        // array_push($newList,$skList);
        // array_push($newList,$tkList);

        $deal_time = array_column($newList, 'deal_time');

        array_multisort($deal_time, SORT_DESC, $newList);

        return [
            'list' => $newList,
        ];
    }

    /**
     * 客户的服务记录
     */
    public function serviceLog($request)
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $startTime = strtotime(date('Y-m-01',time()));
        $endTime = strtotime(date('Y-m-t 23:59:59',time()));

        try {

            $customerId = $request['customer_id'] ?? '';

            $type = $request['type'] ?? '';
            
            $user_id = $request['user_id'] ?? '';

            $shopIds = $request['shopIds'] ?? '';

            $status = $request['status'] ?? '';

            $searchText = $request['searchText'] ?? '';

            $is_evaluation = $request['is_evaluation'] ?? '0';

            $where = [];

            // array_push($where,['create_time','between',"$startTime,$endTime"]);

            if($customerId>0){
                array_push($where,['customer_id','=',$customerId]);
            }

            if($status == '-1'){
                $tagTime = strtotime('-1 month');

                array_push($where,['create_time','>',$tagTime]);
				
				$shop_person_id = Db::name('shop_person')->where('name','虚拟员工核销专用')->column('id');
				array_push($where,['nurse_id_one','not in',$shop_person_id]);
            }

            array_push($where,['is_evaluation','=',$is_evaluation]);

            array_push($where,['service_type','=',1]);
            // if($is_evaluation != ''){
            //     array_push($where,['is_evaluation','=',$is_evaluation]);
            // }else{
            //     array_push($where,['is_evaluation','is null','']);
            // }

            // 搜索
            if(!empty($searchText)){
                $searchWhere = [];

                array_push($searchWhere,['customer_name|telephone','like',"$searchText%"]);
                array_push($searchWhere,['shop_id','in',$shopIds]);

                // echo "<pre>";
                // print_r($searchWhere);
                // echo "</pre>";

                $customerSearch = Db::name('customer')->where($searchWhere)->column('id');

                array_push($where,['customer_id','in',$customerSearch]);
            }

            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";
            // exit;

            if($type==1){
                $permissions = $this->getPermissions($request);

                if($permissions){
                    // 范围权限
                    array_push($where,['shop_id','in',$shopIds]);
                }else{
                    // 个人权限

                    $shop_person_id = Db::name('admin_user')->where('id',$user_id)->value('shop_person_id');

                    $csutomerIds = Db::name('customer')->where('nurse_id','=',$shop_person_id)->column('id');

                    array_push($where,['customer_id','in',$csutomerIds]);
                }
            }

            $dataCount =  Db::name('service_log')->where($where)->count();

            $serviceLogList =  Db::name('service_log')->where($where)->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->order('id DESC')->select()->toArray();

            // echo "<pre>";
            // print_r($serviceLogList);
            // echo "</pre>";
            // exit;

            $cids = array_values(array_unique(array_column($serviceLogList, 'customer_id')));

            $serviceIds = array_values(array_unique(array_column($serviceLogList, 'service_id')));

            $shop_ids = array_values(array_unique(array_column($serviceLogList, 'shop_id')));

            $nurse_ids1 = array_values(array_unique(array_column($serviceLogList, 'nurse_id_one')));

            $nurse_ids2 = array_values(array_unique(array_column($serviceLogList, 'nurse_id_two')));

            $customerInfo = Db::name('customer')->where('id','in',$cids)->column('customer_name,telephone','id');

            $serciceCardInfo = Db::name('service')->where('id','in',$serviceIds)->column('name','id');

            $nurse1 = Db::name('shop_person')->where('id','in',$nurse_ids1)->column('name','id');

            $nurse2 = Db::name('shop_person')->where('id','in',$nurse_ids2)->column('name','id');

            $shops = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name','shop_id');

            $list = [];
            foreach ($serviceLogList as $key => $value) {
                
                $one = [];

                $one['id'] = $value['id'];

                $one['customer_name'] = $customerInfo[$value['customer_id']]['customer_name'] ?? '';

                $one['service_name'] = $serciceCardInfo[$value['service_id']] ?? '';

                $one['nurse1'] = $nurse1[$value['nurse_id_one']] ?? '';

                $one['nurse2'] = $nurse2[$value['nurse_id_two']] ?? '';

                $one['create_time'] =  $value['create_time']>0 ? date('Y-m-d H:i:s',$value['create_time']) : '';

                $one['telephone'] = substr_replace($customerInfo[$value['customer_id']]['telephone'], '****', 3, 4);

                $one['shop'] = $shops[$value['shop_id']] ?? '';

                array_push($list,$one);
            }

            $data = [];

            $data['list'] = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return ['data' => $data];

        } catch (\Throwable $e) {
            return ['error' => $e->getMessage()];
        }
        
    }

    /**
     * 客户管理
     */
    public function getDataList($request)
    {
        $startTime = strtotime(date('Y-m-01',time()));
        $endTime = strtotime(date('Y-m-t 23:59:59',time()));

        $permissions = $this->getPermissions($request);

        $where = [];
        $result = [];

        if($permissions){
            // $data = '范围数据(true)';
            array_push($where,['shop_id','in',$request['shopIds']]);
        }else{
            // $data = '个人数据(false)';
            array_push($where,['shop_id','in',$request['shopIds']]);
            array_push($where,['nurse_id','=',$request['user_id']]);
        }

        // 预约未进店
        $num1 = Db::name('customer')->where($where)
                ->where('first_time','<',1)
                ->where('second_time','<',1)
                ->where('create_time','between',"$startTime,$endTime")
                ->count();


        // ------------------------------------------------------------        
        $model = new ReserveandLost();
        $date = date('Y-m-d',time());


        
        // 成交顾客id
        $cj_customer = $model->cj_customer($request['shopIds'],[]);

        // echo "<pre>";
        // print_r($cj_customer);
        // echo "</pre>";
        // exit;

        //流失预警
        $liushiyujing = $model->warning_customer($cj_customer,$date,'','','');
        $num2 = count($liushiyujing);

        // 流失顾客
        $lost_customer = $model->lost_customer($cj_customer,$date);
        $num3 = count($lost_customer);

        // 流失预警
        // $customerLossModel = new CustomerLossModel();
        // $liushiyujing = [
        //     'is_join_shop' => 4,
        //     'shopIds' => $request['shopIds'],
        //     'user_id' => $request['user_id'],
        //     'onlyDataCounts' => 'yes',
        // ];

        // $dataList = $customerLossModel->getDataList($liushiyujing);
        // $num2 = $dataList['dataCounts'];

    
        // 流失顾客
        // $liushiguke = [
        //     'is_join_shop' => 3,
        //     'shopIds' => $request['shopIds'],
        //     'user_id' => $request['user_id'],
        //     'onlyDataCounts' => 'yes',
        // ];
        // $dataList = $customerLossModel->getDataList($liushiguke);
        // $num3 = $dataList['dataCounts'];

        // 新客未成交
        $num4 = Db::name('customer')->where($where)
                ->where('cj_time','<',1)
                ->where('first_time|second_time','between',"$startTime,$endTime")
                ->count();

        // 生日提醒
        $birthdayStr = strtotime('+1 week');
        $nowTime = time();
        $num5 = Db::name('customer')->where($where)
                ->where('membership_leve','>',0)
                ->where('birthday','between',"$nowTime,$birthdayStr")
                ->count();

        // 

        $result = [
            '0' => [
                'title' => '预约未进店',
                'content' => '提醒昨天和今天未到店的客户',
                'icon' => '2.png',
                'num' => $num1,
                'function' => 'noComeIn'
            ],
            '1' => [
                'title' => '流失预警',
                'content' => '截至到当前事件1个月内未消费顾客书',
                'icon' => '1.png',
                'num' => $num2,
                'function' => 'liushiyj'
            ],
            '2' => [
                'title' => '流失客户',
                'content' => '截至到当前事件4个月内未消费顾客书',
                'icon' => '3.png',
                'num' => $num3,
                'function' => 'liushikh'
            ],
            '3' => [
                'title' => '新客未成交',
                'content' => '当月进店且未成交的顾客',
                'icon' => '2.png',
                'num' => $num4,
                'function' => 'noCJ'
            ],
            '4' => [
                'title' => '生日提醒',
                'content' => '近7天过生日的会员客户',
                'icon' => '4.png',
                'num' => $num5,
                'function' => 'birthday'
            ]
            
        ];

        return ['list' => $result];
    }

    // 获取数据范围权限
    public function getPermissions($request){
        $where = [];
        array_push($where,['id','=',$request['user_id']]);
        $group_id = Db::name('admin_user')->where($where)->value('group_id');

        $hulishis = [74,76,77,78,79,80,98,104,107];

        if(in_array($group_id,$hulishis)){
            $permissions = false; // 个人数据
        }else{
            $permissions = true; // 范围数据
        }

        return $permissions;
    }

    // 添加客户标签
    public function addTag($request){

        $create_time = date('Y-m-d h:i:s',time());

        $where = [];

        array_push($where,['tag_name','=',$request['tagValue']]);
        array_push($where,['customer_id','=',$request['customer_id']]);

        $tagInfo = Db::name('customer_tag')->where($where)->find();

        if(empty($tagInfo)){
            $data = [
                'id'          => '',
                'tag_name'    => $request['tagValue'],
                'customer_id' => $request['customer_id'],
                'staff_name'  => $request['staff_name'],
                'create_time' => $create_time,
                'type'        => 0,
            ];

            $tagId = Db::name('customer_tag')->insertGetId($data);

            $msg = '添加成功！';
        }else{
            $msg = '标签重复！';
        }

        


        return ['result' => $msg];
    }

    // 获取客户标签
    public function getTag($request){

        $where = [];

        array_push($where,['customer_id','=',$request['customer_id']]);
        array_push($where,['type','=',0]);

        $tagArr = Db::name('customer_tag')->where($where)->column('id,tag_name');

        return ['result' => $tagArr];
    }

    // 删除客户标签
    public function deleteTag($request){
        $data['type'] = 1;

        $bool = Db::name('customer_tag')->where(['id'=>$request['id']])->update($data);

        if ($bool !== false) {
            return ['error' => '操作成功', 'data' => []];
        }else{
            return ['error' => '操作失败', 'data' => []];
        }
    }


    // 获取客户列表
    public function getCaseCustomer($request){

        $where = [];

        $customer_id = $request['customer_id'];

        array_push($where,['id','=',$customer_id]);

        // echo "<pre>";
        // print_r($where);
        // echo "</pre>";
        // exit;
        $sex = ['1' => '男', '2' => '女'];

        $customer_list = Db::name('customer')->where($where)->find();

        $customer_list['sex_title'] = $sex[$customer_list['sex']];

        return $customer_list;
    }

    // 员工小程序数据模块-经营数据
    public function getShopStistics($request){

        if($request['time'] == '选择时间'){

            $startTime = strtotime(date('Y-m-01',time()));
            $endTime = strtotime(date('Y-m-t 23:59:59',time()));
    
            $request['startTime'] = $startTime;
            $request['endTime'] = $endTime;

            $st = date('Y-m-01',time());

            $et = date('Y-m-t',time());

        }else{

            $strlength = strlen($request['time']);

            if($strlength>7){

                $startTime = strtotime($request['time']." 00:00:00");

                $endTime = strtotime($request['time']." 23:59:59");

                $st = $request['time'];

                $et = $request['time'];

            }else{
                $t = date('t',strtotime($request['time']));

                $st = $request['time'].'-01';

                $et = $request['time'].'-'.$t;

                $startTime = strtotime($st." 00:00:00");

                $endTime = strtotime($et." 23:59:59");

            }

        }

        $orderModel = new ShopOrderModel();

        $shopModel = new ShopModel();

        // $order = $orderModel->miniHomeOrder($shopIds, $request);

        $is_shop_array = ['2' => 1,'1' =>2];

        $shopIds = json_decode($request['shop_id'],true) ?? array();

        if(is_array($shopIds)){

            $amountData = []; // 总
            $amountNewData = []; // 新
            $amountRepairData = []; // 补
            $amountSData = []; // 实
            $referralData = []; // 转
            $scarData = []; // 疤
            $projectData = []; // 项

            foreach ($shopIds as $key => $value) {
                $newShopIds = [];

                array_push($newShopIds,$value);

                $is_medical = Db::name('shop')->where('shop_id',$value)->value('shop_type');

                $isShop = $is_shop_array[$is_medical];

                $newRequest = [];

                $newRequest['startTime'] = $st;
                $newRequest['endTime'] = $et;
                $newRequest['isShop'] = $isShop;

                $order = $orderModel->miniHomeOrder($newShopIds, $newRequest);

                $shopModelRequest['start_time'] = $st;
                $shopModelRequest['end_time'] = $et;

                $shopModelData = $shopModel->readAdminShopAchievementStatistics($newShopIds,(int)$request['page']="",(int)$request['limit']="",$shopModelRequest); 

                $sData = $shopModelData['list'];

                array_push($amountData,$order['amount']);
                array_push($amountNewData,$order['amountNew']);
                array_push($amountRepairData,$order['amountRepair']);

                array_push($amountSData,$sData[0]['amount']);
                array_push($referralData,$sData[0]['referralMoney']);
                array_push($scarData,$sData[0]['scarMoney']);
                array_push($projectData,$sData[0]['projectMoney']);

            }

            // echo "<pre>";
            // print_r($amountData);
            // echo "</pre>";
            // exit;

            $res = [
                'amount' => bcadd(array_sum($amountData),0,2),

                'amountNew' => bcadd(array_sum($amountNewData),0,2),

                'amountRepair' => bcadd(array_sum($amountRepairData),0,2),

                'amountS' => bcadd(array_sum($amountSData),0,2),

                'referral' => bcadd(array_sum($referralData),0,2),

                'scar' => bcadd(array_sum($scarData),0,2),

                'project' => bcadd(array_sum($projectData),0,2),
            ];

        }else{

            $newShopIds = [];

            array_push($newShopIds,$shopIds);
            
            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->value('shop_type');

            $isShop = $is_shop_array[$is_medical];

            $newRequest = [];

            $newRequest['startTime'] = $startTime;
            $newRequest['endTime'] = $endTime;
            $newRequest['isShop'] = $isShop;

            $order = $orderModel->miniHomeOrder($newShopIds, $newRequest);

            $shopModelRequest['start_time'] = $st;
            $shopModelRequest['end_time'] = $et;

            $shopModelData = $shopModel->readAdminShopAchievementStatistics($newShopIds,(int)$request['page']="",(int)$request['limit']="",$shopModelRequest); 

            $sData = $shopModelData['list'];

            // echo "<pre>";
            // print_r($shopModelData);
            // echo "</pre>";
            // exit;

            $res = [
                'amount' => bcadd($order['amount'],0,2),  //当前店铺集合支付总金额

                'amountNew' => bcadd($order['amountNew'],0,2), //新单

                'amountRepair' => bcadd($order['amountRepair'],0,2), //补单

                'amountS' => bcadd($sData[0]['amount'],0,2), //实收

                'referral' => bcadd($sData[0]['referralMoney'],0,2), //转诊

                'scar' => bcadd($sData[0]['scarMoney'],0,2), //疤痕

                'project' => bcadd($sData[0]['projectMoney'],0,2), //项目
            ];

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-新单数据
    public function getShopStistics1($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];

        // echo "<pre>";
        // print_r($conditions);
        // echo "</pre>";
        // exit;

        $model = new OrderStatistics();

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountNewData = []; // 新单

            foreach ($shopIds as $key => $value) {

                $is_medical = Db::name('shop')->where('shop_id',$value)->field('shop_type,market_id')->find();

                // echo "<pre>";
                // print_r($is_medical);
                // echo "</pre>";
                // exit;

                if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                    // 川渝地区

                    $newsXDMoney = $model->sumShopPayMoneyNewMZ('XD',$value,$is_medical['shop_type'],$startTime,$endTime);
                    
                }else{ 
                    // 非川渝地区

                    $newsXDMoney = $model->sumShopPayMoneyNew('XD',$value,$is_medical['shop_type'],$startTime,$endTime);

                }

                array_push($amountNewData,$newsXDMoney);

            }

            $res = bcadd(array_sum($amountNewData),0,2);

        }else{

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();

            if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                // 川渝地区

                $newsXDMoney = $model->sumShopPayMoneyNewMZ('XD',$shopIds,$is_medical['shop_type'],$startTime,$endTime);
                
            }else{ 
                // 非川渝地区

                $newsXDMoney = $model->sumShopPayMoneyNew('XD',$shopIds,$is_medical['shop_type'],$startTime,$endTime);

            }

            $res = bcadd($newsXDMoney,0,2);

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-补单数据
    public function getShopStistics2($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];

        // echo "<pre>";
        // print_r($conditions);
        // echo "</pre>";
        // exit;

        $model = new OrderStatistics();

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountNewData = []; // 补单

            foreach ($shopIds as $key => $value) {

                $is_medical = Db::name('shop')->where('shop_id',$value)->field('shop_type,market_id')->find();

                // echo "<pre>";
                // print_r($is_medical);
                // echo "</pre>";
                // exit;

                if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                    // 川渝地区

                    $newsXDMoney = $model->sumShopPayMoneyNewMZ('BD',$value,$is_medical['shop_type'],$startTime,$endTime);
                    
                }else{ 
                    // 非川渝地区

                    $newsXDMoney = $model->sumShopPayMoneyNew('BD',$value,$is_medical['shop_type'],$startTime,$endTime);

                }

                array_push($amountNewData,$newsXDMoney);

            }

            $res = bcadd(array_sum($amountNewData),0,2);

        }else{

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();

            if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                // 川渝地区

                $newsXDMoney = $model->sumShopPayMoneyNewMZ('BD',$shopIds,$is_medical['shop_type'],$startTime,$endTime);
                
            }else{ 
                // 非川渝地区

                $newsXDMoney = $model->sumShopPayMoneyNew('BD',$shopIds,$is_medical['shop_type'],$startTime,$endTime);

            }

            $res = bcadd($newsXDMoney,0,2);

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-实收业绩
    public function getShopStistics3($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];

        $shopModel = new ShopModel();

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountShiShou = [];

            foreach ($shopIds as $key => $value) {
                
                $shiShouMoney = $shopModel->amountMoneyAll($value,$startTime,$endTime);

                array_push($amountShiShou,$shiShouMoney);

            }

            $res = bcadd(array_sum($amountShiShou),0,2);

        }else{

            $shiShouMoney = $shopModel->amountMoneyAll($shopIds,$startTime,$endTime);

            $res = bcadd($shiShouMoney,0,2);

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-转诊业绩
    public function getShopStistics4($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];

        $shopModel = new ShopModel();

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountZhuanZhen = []; // 转诊

            foreach ($shopIds as $key => $value) {

                $is_medical = Db::name('shop')->where('shop_id',$value)->field('shop_type,market_id')->find();

                // echo "<pre>";
                // print_r($is_medical);
                // echo "</pre>";
                // exit;

                if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                    // 川渝地区

                    $referralMoney = 0;
                    
                }else{ 
                    // 非川渝地区

                    $referralMoney = $shopModel->referralMoney($value,$is_medical['shop_type'],$startTime,$endTime);

                }

                array_push($amountZhuanZhen,$referralMoney);

            }

            $res = bcadd(array_sum($amountZhuanZhen),0,2);

        }else{

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();

            if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                // 川渝地区

                $referralMoney = 0;
                
            }else{ 
                // 非川渝地区

                $referralMoney = $shopModel->referralMoney($shopIds,$is_medical['shop_type'],$startTime,$endTime);

            }

            $res = bcadd($referralMoney,0,2);

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-疤痕业绩
    public function getShopStistics5($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];

        $shopModel = new ShopModel();

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountScar = []; // 转诊

            foreach ($shopIds as $key => $value) {

                $is_medical = Db::name('shop')->where('shop_id',$value)->field('shop_type,market_id')->find();

                if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                    // 川渝地区

                    $scarMoney = $shopModel->sumShopPayMoneyNewMZ('Bh',$value,$is_medical['shop_type'],$startTime,$endTime);
                    
                }else{ 
                    // 非川渝地区

                    $scarMoney = $shopModel->sumShopPayMoneyNew('Bh',$value,$is_medical['shop_type'],$startTime,$endTime);

                }

                array_push($amountScar,$scarMoney);

            }

            $res = bcadd(array_sum($amountScar),0,2);

        }else{

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();

            if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                // 川渝地区

                $scarMoney = $shopModel->sumShopPayMoneyNewMZ('Bh',$shopIds,$is_medical['shop_type'],$startTime,$endTime);
                
            }else{ 
                // 非川渝地区

                $scarMoney = $shopModel->sumShopPayMoneyNew('Bh',$shopIds,$is_medical['shop_type'],$startTime,$endTime);

            }

            $res = bcadd($scarMoney,0,2);

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-项目业绩
    public function getShopStistics6($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];

        $shopModel = new ShopModel();

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountProject = []; // 转诊

            foreach ($shopIds as $key => $value) {

                $is_medical = Db::name('shop')->where('shop_id',$value)->field('shop_type,market_id')->find();

                if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                    // 川渝地区

                    $projectMoney = $shopModel->sumShopPayMoneyNewMZ('XM',$value,$is_medical['shop_type'],$startTime,$endTime);
                    
                }else{ 
                    // 非川渝地区

                    $projectMoney = $shopModel->sumShopPayMoneyNew('XM',$value,$is_medical['shop_type'],$startTime,$endTime);

                }

                array_push($amountProject,$projectMoney);

            }

            $res = bcadd(array_sum($amountProject),0,2);

        }else{

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();

            if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){ 
                // 川渝地区

                $projectMoney = $shopModel->sumShopPayMoneyNewMZ('XM',$shopIds,$is_medical['shop_type'],$startTime,$endTime);
                
            }else{ 
                // 非川渝地区

                $projectMoney = $shopModel->sumShopPayMoneyNew('XM',$shopIds,$is_medical['shop_type'],$startTime,$endTime);

            }

            $res = bcadd($projectMoney,0,2);

        }

        return $res;

    }

    // 员工小程序数据模块-客户分析
    public function getCustomerStistics($request){

        if($request['time'] == '选择时间'){

            $startTime = strtotime(date('Y-m-01',time()));
            $endTime = strtotime(date('Y-m-t 23:59:59',time()));
    
            $request['startTime'] = $startTime;
            $request['endTime'] = $endTime;

            $st = date('Y-m-01',time());

            $et = date('Y-m-t',time());

        }else{

            $strlength = strlen($request['time']);

            if($strlength>7){

                $startTime = strtotime($request['time']." 00:00:00");

                $endTime = strtotime($request['time']." 23:59:59");

                $st = $request['time'];

                $et = $request['time'];

            }else{

                $t = date('t',strtotime($request['time']));

                $st = $request['time'].'-01';

                $et = $request['time'].'-'.$t;

                $startTime = strtotime($st." 00:00:00");

                $endTime = strtotime($et." 23:59:59");

            }

        }

        $is_shop_array = ['2' => 1,'1' =>2];

        $shopIds = json_decode($request['shop_id'],true) ?? array();

        $newShopIds = [];        

        if(is_array($shopIds)){

            foreach ($shopIds as $key => $value) {

                array_push($newShopIds,$value);
                
            }

        }else{

            // $newShopIds = [];

            array_push($newShopIds,$shopIds);

        }

        $newRequest['startTime'] = $startTime;

        $newRequest['endTime'] = $endTime;

        $newRequest['shopIds'] = $newShopIds;

        $model = new MiniStisticsModel();

        $newVip = $model->getNewVip($newRequest); // 新增会员数

        $comeInByOffLine = $model->getComeInNum(0,[46,47,48,583,608],$newRequest); // 门头外联进店

        $comeInByZhuan = $model->getComeInNum(0,[49],$newRequest); // 转介绍进店

        $comeInByOnLine = $model->getComeInNum(1,[46,47,48,49,583,608],$newRequest); // 网络进店

        $cj_num_bh = $model->getCjNum(1,$newRequest); // 疤痕成交数

        $cj_num_xm = $model->getCjNum(2,$newRequest); // 项目成交数

        $jd_num_bh = $model->getComeInScarOrPorject([1,2,3,4,5,6,7,8,10],$newRequest); // 疤痘进店数

        $jd_num_xm = $model->getComeInScarOrPorject([9,11,12],$newRequest); // 项目进店数

        if($jd_num_bh['count']>0){

            $cj_rate_bh = bcmul(bcdiv($cj_num_bh['count'],$jd_num_bh['count'],4),100,2)."%";

        }else{

            $cj_rate_bh = "0.00%";

        }
        
        if($jd_num_xm['count']>0){

            $cj_rate_xm = bcmul(bcdiv($cj_num_xm['count'],$jd_num_xm['count'],4),100,2)."%";

        }else{

            $cj_rate_xm = "0.00%";

        }

        $res = [
            'newVip' => $newVip['count'],

            'jd_mentou' => $comeInByOffLine['count'],

            'jd_zhuan' => $comeInByZhuan['count'],

            'jd_wangluo' => $comeInByOnLine['count'],

            'cj_num_bh' => $cj_num_bh['count'],

            'cj_num_xm' => $cj_num_xm['count'],

            'jd_num_bh' => $jd_num_bh['count'],

            'jd_num_xm' => $jd_num_xm['count'],

            'cj_rate_bh' => $cj_rate_bh,

            'cj_rate_xm' => $cj_rate_xm,
        ];

        return $res;
    }

    // 员工小程序数据模块-员工数据
    public function getStaffStistics($request)
    {

        

        if($request['time'] == '选择时间'){

            $startTime = strtotime(date('Y-m-01',time()));

            $endTime = strtotime(date('Y-m-t 23:59:59',time()));
    
            $request['startTime'] = $startTime;
            
            $request['endTime'] = $endTime;

        }else{

            $strlength = strlen($request['time']);

            if($strlength>7){

                $startTime = strtotime($request['time']." 00:00:00");

                $endTime = strtotime($request['time']." 23:59:59");

            }else{

                $t = date('t',strtotime($request['time']));

                $st = $request['time'].'-01';

                $et = $request['time'].'-'.$t;

                $startTime = strtotime($st." 00:00:00");

                $endTime = strtotime($et." 23:59:59");

            }

        }

        $newRequest['startTime'] = $startTime;

        $newRequest['endTime'] = $endTime;

        // 员工列表
        $staffIds = json_decode($request['staffList'],true) ?? array();

        $newStaffIds = [];

        foreach ($staffIds as $key => $value) {

            array_push($newStaffIds,$value);

        }

        $newRequest['staffList'] = $newStaffIds;

        // 门店列表
        $shopIds = json_decode($request['shop_id'],true) ?? array();

        $newShopIds = [];    

        array_push($newShopIds,$shopIds);

        $newRequest['shop_id'] = $newShopIds;

        $model = new MiniStisticsModel();

        if($request['position_id'] == 9){
            
            $newOrder = $model->newOrder($newRequest); // 新单

            $repairOrder = $model->repairOrder($newRequest); // 补单

            $experience = $model->experience($newRequest); // 体验

            $serviceLog = $model->serviceLog($newRequest); // 护理次数

            $serviceNums = $model->serviceNums($newRequest); // 护理人数

            $zhuanNums = $model->zhuanNums($newRequest); // 转介绍业绩

            $waiLianNums = $model->waiLianNums($newRequest); // 外联人数

            $res = [
                
                'newOrder' => $newOrder[0]['newOrder'],

                'repairOrder' => $repairOrder[0]['repairOrder'],

                'experience' => $experience[0]['experience'],

                'serviceLog' => $serviceLog[0]['serviceLog'],

                'serviceNums' => $serviceNums[0]['serviceNums'],

                'zhuanNums' => $zhuanNums[0]['zhuanNums'],

                'waiLianNums' => $waiLianNums[0]['waiLianNums'],

            ];

        }else{

            if($request['tabTitle'] == '新单业绩'){

                $res = $model->newOrder($newRequest);
    
            }
    
            if($request['tabTitle'] == '补单业绩'){
    
                $res = $model->repairOrder($newRequest);
    
            }
    
            if($request['tabTitle'] == '体验成交'){
    
                $res = $model->experience($newRequest);
    
            }
    
            if($request['tabTitle'] == '护理次数'){
    
                $res = $model->serviceLog($newRequest);
    
            }
    
            if($request['tabTitle'] == '护理人数'){
    
                $res = $model->serviceNums($newRequest);
    
            }
    
            if($request['tabTitle'] == '转介绍数'){
    
                $res = $model->zhuanNums($newRequest);
    
            }
    
            if($request['tabTitle'] == '外联人数'){
    
                $res = $model->waiLianNums($newRequest);
    
            }

        }

        

        

        // $request['msg'] = 'model';

        return [

            'position_id' => $request['position_id'],
            
            'title' => $request['tabTitle'],

            'list' => $res,

        ];
    }

    // 时间-门店 转换函数
    public function getTime($request){

        // 时间
        if($request['time'] == '选择时间'){

            $startTime = strtotime(date('Y-m-01',time()));
            $endTime = strtotime(date('Y-m-t 23:59:59',time()));
    
            $request['startTime'] = $startTime;
            $request['endTime'] = $endTime;

            $st = date('Y-m-01',time());

            $et = date('Y-m-t',time());

        }else{

            $strlength = strlen($request['time']);

            if($strlength>7){

                $startTime = strtotime($request['time']." 00:00:00");

                $endTime = strtotime($request['time']." 23:59:59");

                $st = $request['time'];

                $et = $request['time'];

            }else{
                $t = date('t',strtotime($request['time']));

                $st = $request['time'].'-01';

                $et = $request['time'].'-'.$t;

                $startTime = strtotime($st." 00:00:00");

                $endTime = strtotime($et." 23:59:59");

            }

        }

        // 门店
        $shopIds = json_decode($request['shop_id'],true) ?? array();

        return [

            'startTime' => $startTime, // 开始时间戳

            'endTime' => $endTime, // 结束时间戳

            'st' => $st, //开始日期

            'et' => $et, // 结束日期

            'shopIds' => $shopIds, // 门店
        ];

    }

    // 问卷调查是否展示
    public function isQuestion($request){

        $customer_id = $request['customer_id'];

        $cj_time = Db::name('customer')->where('id',$customer_id)->value('cj_time');

        if($cj_time>0){

            $msg = "成交顾客";

            $newTime = time();

            $timeStr = bcsub($newTime,$cj_time,0);

            $days = bcdiv($timeStr,86400,0);

            switch ($days) {
                case $days >= 300: // 成交10个月
                     $status = 10;
                     break;
                case $days >= 150: // 成交5个月
                     $status = 5;
                     break;
                case $days >= 90: // 成交3个月
                     $status = 3;
                     break;
                case $days >= 30: // 成交1月
                     $status = 1;
                     break;
            }

            // echo $days;

        }else{

            $msg = "未成交顾客";

        }

        return [
            
            'msg'  => $msg,

            'data' => $cj_time,

            'days' => $days,

            'status' => $status,

        ];

    }

    /**
     * 获取问卷调查表
     * 
     */
    public function getQuestionnaire($request){

        $status = $request['status'] ?? '';

        $where = [];

        array_push($where,['status','=',$status]);

        $questionnaire = Db::name('questionnaire')->where($where)->column('qusetion_ids,id');

        // echo "<pre>";
        // print_r($questionnaire);
        // echo "</pre>";
        // exit;

        $question_list = explode(',',$questionnaire[0]['qusetion_ids']); // 题目列表

        $questionShow = [];

        foreach ($question_list as $key => $value) {

            $showItem = [];

            $where = [];

            array_push($where,['id','=',$value]);
            
            $question = Db::name('question')->where($where)->column('question_describe,question_answer,status');

            // echo "<pre>";
            // print_r($question);
            // echo "</pre>";
            // exit;

            $showItem['itemId'] = bcadd($key,1,0);

            $showItem['question_describe'] = $question[0]['question_describe'];

            $showItem['status'] = $question[0]['status'];

            $answer_list = explode(',',$question[0]['question_answer']); // 答案列表

            $answer_Show = [];

            foreach ($answer_list as $k => $v) {

                $answerItem = [];
                
                $where = [];

                array_push($where,['id','=',$v]);

                $answer_info = Db::name('question_answer')->where($where)->column('describe,score');

                // echo "<pre>";
                // print_r($answer_info);
                // echo "</pre>";
                // exit;

                $answerItem['num'] = bcadd($k,1,0);

                $answerItem['describe'] = $answer_info[0]['describe'] ?? '';

                $answerItem['score'] = $answer_info[0]['score'] ?? '';

                array_push($answer_Show,$answerItem);

            }

            $showItem['question_answer'] = $answer_Show;

            array_push($questionShow,$showItem);

        }

        // echo "<pre>";
        // print_r($questionShow);
        // echo "</pre>";
        // exit;

        $data = [];

        $data['id'] = $questionnaire[0]['id'];

        $data['list'] = $questionShow;

        return $data;
    }

    // 获取员工小程序-我的预约-列表
    public function getStaffBookList($request):array
    {
        $type = $request['type'];

		/* echo "<pre>";
        print_r($request);
        echo "</pre>";
        exit; */

        $date = $request['date'] ?? '';
        
        if($type == 'PC'){

            // if($request['shopIds']){

            // }

            $user_id = $request['user_id'];

            $shop_person_id = Db::name('admin_user')->where('id',$user_id)->value('shop_person_id');

        }else{

            $shop_person_id = $request['shop_person_id'];

        }
        
        // strtotime();

        if($date){
            $time = $date;
        }else{
            $time = date('Y-m-d',time());
        }
        
		
        $personIds = Db::name('shop_person')->column('id','name');
		
        // 未到点的预约

        $where = [];


        if($type == 'future'){
			/* array_push($where,['status','=',0]);
			
			array_push($where,['shop_person_id','=',$shop_person_id]);
			
			array_push($where,['yy_time','<',$time]); */

            $start_time = strtotime($time);

            $end_time = strtotime($time." 23:59:59");
			
			
            array_push($where,['status','=',0]);

            $station_id = Db::name('shop_person')->where('id',$shop_person_id)->value('station_id');

            // var_dump($station_id);exit;

            if($station_id == '3'){
			
			    $shop_id = $request['shop_id'];

                if($shop_id){

                    array_push($where,['shop_id','=',$shop_id]);

                }

            }else{

                array_push($where,['shop_person_id','=',$shop_person_id]);

            }

            array_push($where,['is_use','=',0]);

            array_push($where,['yy_time','between',"$start_time,$end_time"]); 

        }elseif($type == 'past'){

            // 当日初始时间
            // $InitialTime = strtotime(date("Y-m-d",time()));

            $start_time = strtotime($time);

            $end_time = strtotime($time." 23:59:59");
			
            array_push($where,['status','=',0]);

            $station_id = Db::name('shop_person')->where('id',$shop_person_id)->value('station_id');

            // var_dump($station_id);exit;

            if($station_id == '3'){
			
			    $shop_id = $request['shop_id'];

                if($shop_id){

                    array_push($where,['shop_id','=',$shop_id]);

                }

            }else{

                array_push($where,['shop_person_id','=',$shop_person_id]);

            }

            // array_push($where,['shop_person_id','=',$shop_person_id]);

            // array_push($where,['yy_time','<',$InitialTime]);

            array_push($where,['is_use','=',1]);

            array_push($where,['yy_time','between',"$start_time,$end_time"]); 

        }elseif($type == 'PC'){

            $shopIds = $request['shopIds'];
			
			$shop_id = $request['shop_id'];

            $customer_name = $request['customer_name'];
			
			$name = $request['name'];
			
			$dealTime = $request['deal_time'];
			
			$status = $request['status'];

            if($shopIds){

                array_push($where,['b.shop_id','in',$shopIds]);

            }
			
			if($shop_id){
				array_push($where,['b.shop_id','=',$shop_id]);
			}
			//查询客户
            if($customer_name){

                array_push($where,['c.customer_name|c.telephone','like',$customer_name]);

            }
			//查询预约护理师
			if($name){
				
				$shopPresonId = $personIds[$name];
				
				array_push($where,['b.shop_person_id','=',$shopPresonId]);
			}
			
			//查询预约时间
			
			if($dealTime){
				
				$startTime = strtotime($dealTime);
				$endTime = strtotime($dealTime)+86399;
				
				array_push($where,['b.yy_time','>=',$startTime]);
				array_push($where,['b.yy_time','<=',$endTime]);
			}
			
			//查询状态信息 已核销 1 ;待核销 2 ; 已过期 3
			if($status){
				
				$tommerDay = strtotime($time);
				
				if($status==1){ 
					array_push($where,['b.status','=',0]);
					array_push($where,['b.is_use','=',1]);
				}
				if($status==2){
					array_push($where,['b.status','=',0]);
					array_push($where,['b.is_use','=',0]);
					array_push($where,['b.yy_time','>=',$tommerDay]);
					
				}
				//已过期
				if($status==3){ 
					array_push($where,['b.status','=',0]);
					array_push($where,['b.is_use','=',0]);
					array_push($where,['b.yy_time','<',$tommerDay]);
				}
				if($status==4){
					array_push($where,['b.is_use','=',0]);
					array_push($where,['b.status','=',1]);
				}
				
			}
        }
		
        if($type == 'PC'){
            
          /* echo "<pre>";
            print_r($where);
            echo "</pre>";
             exit; */
            $field = ['b.customer_id','b.shop_person_id','b.shop_id','b.yy_time','b.create_time','b.is_use_time','b.status','b.is_use'];

            $dataCount = Db::name('books')->alias('b')
                    ->join('customer c', 'c.id=b.customer_id', 'LEFT')
                    ->where($where)->count();

            $list = Db::name('books')->alias('b')
                ->join('customer c', 'c.id=b.customer_id', 'LEFT')
                ->where($where)
                ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                ->field($field)
                ->order('b.yy_time DESC')
                ->select()->toArray();

        }else{
		
			/* if($type == 'past'){
				echo "<pre>";
				print_r($where);
				echo "</pre>";
			}
            */
            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";
            // exit;

            // $dataCount = '';

            $list = Db::name('books')->where($where)->order('id DESC')->select()->toArray();

        }
        

        /* echo "<pre>";
        print_r($list);
        echo "</pre>";
        exit; */
        

        $customer_ids = array_values(array_unique(array_column($list,'customer_id')));

        $shopPersonIds = array_values(array_unique(array_column($list,'shop_person_id')));

        $shopIds = array_values(array_unique(array_column($list,'shop_id')));

        $customer_info = Db::name('customer')->where('id','in',$customer_ids)->column('customer_name,telephone,membership_leve','id');

        // 获取客户的openid和微信头像等数据
        $open_info = Db::name('mini_program_fans')->where('customerId','in',$customer_ids)->column('avatarUrl,openId','customerId');

        $staff_info = Db::name('shop_person')->where('id','in',$shopPersonIds)->column('name','id');

        // 获取门店名称
        $shop_names = Db::name('shop')->where('shop_id','in',$shopIds)->column('shop_name','shop_id');

        // echo "<pre>";
        // print_r($staff_info);
        // echo "</pre>";
        // exit;

        $showList = [];

        foreach ($list as $key => $value) {

            // 预约时长
            $length = '';

            $yy_time_str = $value['yy_time_str'] ?? '';

            if($yy_time_str){

                $yy_time_arr = explode(',',$value['yy_time_str']);

                $length = count($yy_time_arr)*0.5;

                $end_time = date('H:i',($value['yy_time']+(1800*count($yy_time_arr))));

            }else{

                $end_time = date('H:i',($value['yy_time']+1800));

                $length = 0.5;

            }
        
            $one = [];

            $one['customer_name'] = $customer_info[$value['customer_id']]['customer_name'] ?? '';

            $one['telephone'] = $customer_info[$value['customer_id']]['telephone'] ?? '';

            $one['shop_name'] = $shop_names[$value['shop_id']] ?? '';

            $one['membership_leve'] = $customer_info[$value['customer_id']]['membership_leve'] ?? '';

            $one['staff_name'] = $staff_info[$value['shop_person_id']];

            // $one['yy_time'] = date('Y-m-d H:i',$value['yy_time']);
            $one['yy_time'] = date('Y-m-d H:i',$value['yy_time']) ?? '';

            $one['yy_time_str'] = $value['yy_time_str'] ?? '';

            $one['yy_length'] = $length;

            $one['openId'] = $open_info[$value['customer_id']]['openId']?? '';

            $one['avatarUrl'] = $open_info[$value['customer_id']]['avatarUrl']?? '';

            $one['create_time'] = date('Y-m-d H:i:s',$value['create_time']);

            $one['is_use_time'] = $value['is_use_time'] > 0 ? date('Y-m-d H:i:s',$value['is_use_time']) : '' ;

            $one['status'] = $value['status'];

            $one['is_use'] = $value['is_use'];

            if($value['status'] == '0'){

                if($value['is_use'] == '0'){

                    if($time <= $one['yy_time']){

                        $one['jindu'] = '待核销';

                    }else{

                        $one['jindu'] = '已过期';
    
                    }

                }else{

                    $one['jindu'] = '已核销';

                }

            }else{

                $one['jindu'] = '已取消';

            }

            array_push($showList,$one);

        }

        // echo "当前日期：".$time;

        // echo "<pre>";
        // print_r($showList);
        // echo "</pre>";
        // exit;

        $data = [];

        if($type == 'PC'){

            $data['dataCount'] = $dataCount;

        }
        

        $data['list'] = $showList;

        return $data;
    }

}